﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace NativeCode.Core.Extensions
{
	public static class EnumerableExtensions
	{
		/// <summary>
		/// Slices an IEnumerable<T> into multiple IEnumerable<T>'s based on the size you want
		/// each IEnumerable<T> to be.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="source"></param>
		/// <param name="size"></param>
		/// <returns></returns>
		public static IEnumerable<IEnumerable<T>> Slice<T>(this IEnumerable<T> source, int size)
		{
			return source.Where((x, i) => i%size == 0).Select((x, i) => source.Skip(i*size).Take(size));
		}

		public static IEnumerable<T> DistinctBy<T, TV>(this IEnumerable<T> enumerable, Func<T, TV> selector)
		{
			return enumerable.Distinct(new DistinctComparer<T, TV>(selector));
		}

		#region Nested type: DistinctComparer

		public class DistinctComparer<T, TV> : IEqualityComparer<T>
		{
			private readonly Func<T, TV> _selector;

			public DistinctComparer(Func<T, TV> selector)
			{
				_selector = selector;
			}

			#region Implementation of IEqualityComparer<T>

			public bool Equals(T x, T y)
			{
				return _selector(x).Equals(_selector(y));
			}

			public int GetHashCode(T obj)
			{
				return _selector(obj).GetHashCode();
			}

			#endregion
		}

		#endregion
	}
}